import type { AsyncData, UseFetchOptions } from "#app";

type TMethods = "GET" | "POST";

const BASE_URL = "http://codercba.com:9060/juanpi/api/";

export interface IResultData<T> {
    code: number;
    data: T;
}

class HYRequest {
    request<T = any>(url: string, method: TMethods, data?: any, options?: UseFetchOptions<T>) {
        const newOptions: UseFetchOptions<T> = {
            baseURL: BASE_URL,
            method: method,
            ...options,
        };

        // 判断是什么请求
        if (method === "GET") {
            newOptions.query = data;
        } else if (method === "POST") {
            newOptions.body = data;
        }

        return useFetch(url, newOptions);

        /* return new Promise((resolve, reject) => {
            useFetch(url, newOptions)
                .then(res => resolve(res))
                .catch(error => reject(error));
        }); */
    }

    get<T = any>(url: string, params?: any, options?: UseFetchOptions<T>) {
        return this.request(url, "GET", params, options);
    }

    post<T = any>(url: string, data?: any, options?: UseFetchOptions<T>) {
        return this.request(url, "POST", data, options);
    }
}

export default new HYRequest();
